#CalHamletV1.py
def getText():       #定义一个函数getText，能够获得文本的具体信息
    txt=open("hamlet.txt","r").read()   #打开文件的代码
    txt=txt.lower()   #把所有的英文字符改成小写
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_{|}·~':  #去掉文本中的特殊符号
        txt=txt.replace(ch,"")    #将特殊符号替换成空格
    return txt

hamletTxt=getText()
words=hamletTxt.split()   #使文本变列表
counts={}
for word in words:
    counts[word]=counts.get(word,0)+1  #遍历列表 计算次数
    items=list(counts.items())     
    items.sort(key=lambda x:x[1],reverse=True)   #给列表排序
    for i in range(10):   #把出现次数最多的前十个单词打印出来
        word,count=items[i]
        print("{0:,10}{1:>5}".format(word,count))


#CalThreeKingdomsV1.py
import jieba  #调用jieba库
txt=open("threekingdoms.txt","r",encoding="utf-8").read()
words=jieba.lcut(txt)   #分词处理，形成一个列表类型的带有所有单词的列表words
counts={}  #构造一个词典
for word in words:  #遍历words中的每一个中文单词并计数
    if len(word)==1:
        continue
    else:
        counts[word]=counts.get(word,0)+1
items=list(counts.items())  #将带有技术的字典counts转换为列表类型
items.sort(key=lambda x:x[1],reverse=True)  #对列表进行排序
for i in range(15):    #将前15位单词打印输出
    word,count=items[i]
    print("{0:<10}{1:>5}".format(word,count))


#CalThreeKingdomsV2.py
import jieba
txt=open("threekingdoms.txt","r",encoding="utf-8").read()
excludes={"将军","却说","荆州","二人","不可","不能","如此"}
words=jieba.lcut(txt)
counts={}
for word in words:
    if len(word)==1:
        continue
    elif word=="诸葛亮" or word=="孔明曰":
        rword="孔明"
    elif word=="关羽" or word=="云长":
        rword="关羽"  
    elif word=="玄德" or word=="玄德曰":
        rword="刘备"
    elif word=="孟德" or word=="丞相曰":
        rword="曹操"
    else:
        rword=word
    counts[word]=counts.get(word,0)+1
for word in excludes:
    del counts[word]
items=list(counts.items())  #将带有技术的字典counts转换为列表类型
items.sort(key=lambda x:x[1],reverse=True)  #对列表进行排序
for i in range(10):    #将前15位单词打印输出
    word,count=items[i]
    print("{0:<10}{1:>5}".format(word,count))